{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "499d90b1",
   "metadata": {},
   "source": [
    "# 百度AI开放平台-OCR(光学文字识别)\n",
    "## 我实践\n",
    "## 通用文字识别\n",
    "* 接口描述\n",
    "> 在通用文字识别的基础上，提供更高精度的识别服务，支持更多语种识别（丹麦语、荷兰语、马来语、瑞典语、印尼语、波兰语、罗马尼亚语、土耳其语、希腊语、匈牙利语、泰语、越语、阿拉伯语、印地语及部分中国少数民族语言），并将字库从1w+扩展到2w+，能识别所有常用字和大部分生僻字。\n",
    "\n",
    "* 请求示例\n",
    "\n",
    "> HTTP 方法：POST\n",
    "\n",
    "> 请求URL： https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\n",
    "* 请求参数\n",
    "> 1.url参数-token\n",
    "> 2. 图片参数-图片文件\n",
    "\n",
    "* 示例代码;\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a1802660",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "c66f3538",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>参数</th>\n",
       "      <th>是否必选</th>\n",
       "      <th>类型</th>\n",
       "      <th>可选值范围</th>\n",
       "      <th>说明</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>image</td>\n",
       "      <td>和 url/pdf_file 三选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图像数据，base64编码后进行urlencode，要求base64编码和urlencode...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>url</td>\n",
       "      <td>和 image/pdf_file 三选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>图片完整url，url长度不超过1024字节，url对应的图片base64编码后大小不超过1...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>pdf_file</td>\n",
       "      <td>和 image/url 三选一</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>PDF文件，base64编码后进行urlencode，要求base64编码和urlencod...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>pdf_file_num</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>-</td>\n",
       "      <td>需要识别的PDF文件的对应页码，当 pdf_file 参数有效时，识别传入页码的对应页面内容...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>language_type</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>auto_detect CHN_ENGENGJAPKORFRESPAPORGERITARUS...</td>\n",
       "      <td>识别语言类型，默认为CHN_ENG可选值包括：- auto_detect：自动检测语言，并识...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>detect_direction</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>true/false</td>\n",
       "      <td>是否检测图像朝向，默认不检测，即：false。朝向是指输入图像是正常方向、逆时针旋转90/1...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>paragraph</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>true/false</td>\n",
       "      <td>是否输出段落信息</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>probability</td>\n",
       "      <td>否</td>\n",
       "      <td>string</td>\n",
       "      <td>true/false</td>\n",
       "      <td>是否返回识别结果中每一行的置信度</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                 参数                  是否必选      类型  \\\n",
       "0             image    和 url/pdf_file 三选一  string   \n",
       "1               url  和 image/pdf_file 三选一  string   \n",
       "2          pdf_file       和 image/url 三选一  string   \n",
       "3      pdf_file_num                     否  string   \n",
       "4     language_type                     否  string   \n",
       "5  detect_direction                     否  string   \n",
       "6         paragraph                     否  string   \n",
       "7       probability                     否  string   \n",
       "\n",
       "                                               可选值范围  \\\n",
       "0                                                  -   \n",
       "1                                                  -   \n",
       "2                                                  -   \n",
       "3                                                  -   \n",
       "4  auto_detect CHN_ENGENGJAPKORFRESPAPORGERITARUS...   \n",
       "5                                         true/false   \n",
       "6                                         true/false   \n",
       "7                                         true/false   \n",
       "\n",
       "                                                  说明  \n",
       "0  图像数据，base64编码后进行urlencode，要求base64编码和urlencode...  \n",
       "1  图片完整url，url长度不超过1024字节，url对应的图片base64编码后大小不超过1...  \n",
       "2  PDF文件，base64编码后进行urlencode，要求base64编码和urlencod...  \n",
       "3  需要识别的PDF文件的对应页码，当 pdf_file 参数有效时，识别传入页码的对应页面内容...  \n",
       "4  识别语言类型，默认为CHN_ENG可选值包括：- auto_detect：自动检测语言，并识...  \n",
       "5  是否检测图像朝向，默认不检测，即：false。朝向是指输入图像是正常方向、逆时针旋转90/1...  \n",
       "6                                           是否输出段落信息  \n",
       "7                                   是否返回识别结果中每一行的置信度  "
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pd.read_html('https://ai.baidu.com/ai-doc/OCR/1k3h7y3db')[2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "44579768",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'refresh_token': '25.2f257db9a9e28c157ecc0d0896af4d94.315360000.1965127628.282335-25954641', 'expires_in': 2592000, 'session_key': '9mzdCSM4LGZCIsF0u1uQ105UFNLl4/33/u4uwXw1IYnGiO6izCXc8w13CaOkTnfWO0wT2xS5UWbB1Bg7j1MzbmNklbJ4xw==', 'access_token': '24.251299b0c294ddcd92317e502256b415.2592000.1652359628.282335-25954641', 'scope': 'public vis-ocr_ocr brain_ocr_scope brain_ocr_general brain_ocr_general_basic vis-ocr_business_license brain_ocr_webimage brain_all_scope brain_ocr_idcard brain_ocr_driving_license brain_ocr_vehicle_license vis-ocr_plate_number brain_solution brain_ocr_plate_number brain_ocr_accurate brain_ocr_accurate_basic brain_ocr_receipt brain_ocr_business_license brain_solution_iocr brain_qrcode brain_ocr_handwriting brain_form brain_ocr_passport brain_ocr_vat_invoice brain_numbers brain_ocr_business_card brain_ocr_train_ticket brain_ocr_taxi_receipt vis-ocr_household_register vis-ocr_vis-classify_birth_certificate vis-ocr_台湾通行证 vis-ocr_港澳通行证 vis-ocr_机动车购车发票识别 vis-ocr_机动车检验合格证识别 vis-ocr_车辆vin码识别 vis-ocr_定额发票识别 vis-ocr_保单识别 vis-ocr_机打发票识别 vis-ocr_行程单识别 brain_ocr_vin brain_ocr_quota_invoice brain_ocr_birth_certificate brain_ocr_household_register brain_ocr_HK_Macau_pass brain_ocr_taiwan_pass brain_ocr_vehicle_invoice brain_ocr_vehicle_certificate brain_ocr_air_ticket brain_ocr_invoice brain_ocr_insurance_doc brain_formula brain_seal brain_ocr_facade brain_ocr_meter brain_doc_analysis brain_ocr_webimage_loc brain_ocr_medical_paper brain_ocr_doc_analysis_office brain_vat_invoice_verification brain_ocr_medical_detail brain_vehicle_registration_certificate brain_ocr_online_taxi_itinerary brain_ocr_multi_idcard brain_ocr_mixed_multi_vehicle brain_ocr_weigth_note brain_ocr_ multiple_invoice wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online', 'session_secret': '42be1f0a3b8e3fd49568c52a4b4ac491'}\n"
     ]
    }
   ],
   "source": [
    "import requests \n",
    "\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "payload = {\n",
    "    'grant_type':'client_credentials',\n",
    "    'client_id':'etVvBg1B2xMKAjET5MrXhG1K',\n",
    "    'client_secret':'EWCKgFN3btZxlYt9bWYSgpWUDAdS4eiG'\n",
    "}\n",
    "response = requests.get(host,params=payload)\n",
    "if response:\n",
    "    print(response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "8738077b",
   "metadata": {},
   "outputs": [],
   "source": [
    "jiaxin_AT = response.json()['access_token']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "79a83ea2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '美的历史'}, {'words': 'STORIA DELLA BELLEZZA'}, {'words': 'Umberto Eco'}, {'words': '【意大利】翁贝托·艾柯◎编著'}, {'words': '彭淮栋◎译'}], 'words_result_num': 5, 'log_id': 1513861328019211764}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用文字识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('shuji.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':jiaxin_AT,\n",
    "    'image':img,\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15fcb60b",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 实践A-1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "88e6d0ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 网络图片文字识别\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0e29642d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'words': '网'}, {'words': '香辣'}, {'words': '网'}], 'words_result_num': 3, 'log_id': 1513861753022662737}\n"
     ]
    }
   ],
   "source": [
    "## 实践2\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/webimage\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('yishu.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':jiaxin_AT,\n",
    "    'image':img,\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d75df439",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 手写文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "eb107447",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'location': {'top': 115, 'left': 33, 'width': 575, 'height': 100}, 'words': '抗渡一线的所有工年者:'}, {'location': {'top': 221, 'left': 73, 'width': 413, 'height': 102}, 'words': '感谢所有兴和热'}, {'location': {'top': 342, 'left': 75, 'width': 462, 'height': 99}, 'words': '初愿所有人平安'}, {'location': {'top': 480, 'left': 146, 'width': 182, 'height': 47}, 'words': '加油?'}], 'words_result_num': 4, 'log_id': 1513861796975948750}\n"
     ]
    }
   ],
   "source": [
    "## 实践3\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('shouxie.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':jiaxin_AT,\n",
    "    'image':img,\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ce1ff713",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 二维码识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "81c242f4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'codes_result': [{'text': ['你在干嘛？'], 'type': 'QR_CODE'}], 'codes_result_num': 1, 'log_id': 1513862483149274724}\n"
     ]
    }
   ],
   "source": [
    "## 实践4\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/qrcode\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('er.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':jiaxin_AT,\n",
    "    'image':img,\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6da4d1a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 卡片类文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "816839bd",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result': [{'location': {'top': 76, 'left': 87, 'width': 121, 'height': 80}, 'words': '广期'}, {'location': {'top': 226, 'left': 146, 'width': 336, 'height': 147}, 'words': '未)来可期'}, {'location': {'top': 277, 'left': 153, 'width': 40, 'height': 30}, 'words': 'wel '}, {'location': {'top': 243, 'left': 416, 'width': 62, 'height': 88}, 'words': '期'}, {'location': {'top': 356, 'left': 261, 'width': 140, 'height': 39}, 'words': 'The future say be exprectnd '}], 'words_result_num': 5, 'log_id': 1513862977111072886}\n"
     ]
    }
   ],
   "source": [
    "## 实践5\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/ocr/v1/handwriting\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('ka.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':jiaxin_AT,\n",
    "    'image':img,\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7439911",
   "metadata": {},
   "outputs": [],
   "source": [
    "## 财务类文字识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "70b663e4",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'words_result_num': 43, 'words_result': {'AmountInWords': '壹拾叁万柒仟捌佰元整', 'InvoiceNumConfirm': '58970228', 'CommodityEndDate': [], 'CommodityVehicleType': [], 'CommodityStartDate': [], 'CommodityPrice': [{'row': '1', 'word': '130000.00'}], 'NoteDrawer': '王松', 'SellerAddress': '北京市广场路12号010-57386237', 'CommodityNum': [{'row': '1', 'word': '1'}], 'SellerRegisterNum': '91118624538783725C', 'MachineCode': '928805152362', 'Remarks': '校10295211051351704563391118624538783725', 'SellerBank': '工行北京民和路支行0702011278945666323', 'CommodityTaxRate': [{'row': '1', 'word': '6%'}], 'TotalTax': '7800.00', 'InvoiceCodeConfirm': '1100193460', 'CheckCode': '928805152362', 'InvoiceCode': '1100193460', 'InvoiceDate': '2019年07月01日', 'PurchaserRegisterNum': '910340111750782058', 'InvoiceTypeOrg': '北京增值税专用发票', 'OnlinePay': '', 'Password': '>*0604/52/+90*+8099>3795+*039>7/1062<><**13+7>71*<4</-21<+82018<30031-+55+7>>*69>90/04/52/+90*+8099>3795', 'Agent': '否', 'AmountInFiguers': '137800.00', 'PurchaserBank': '工行北京民和路支行0702011278945666323', 'Checker': '梁娟娟', 'City': '', 'TotalAmount': '130000.00', 'CommodityAmount': [{'row': '1', 'word': '130000.00'}], 'PurchaserName': '北京市金迪房地产开发有限公司', 'CommodityType': [{'row': '1', 'word': '130000.00'}], 'Province': '北京', 'InvoiceType': '专用发票', 'SheetNum': '第三联：发票联', 'PurchaserAddress': '北京市民和路35号华腾大厦010-86388318', 'CommodityTax': [{'row': '1', 'word': '7800.00'}], 'CommodityPlateNum': [], 'CommodityUnit': [], 'Payee': '秦丽', 'CommodityName': [{'row': '1', 'word': '*设计服务*园林设计费'}], 'SellerName': '北京锦绣园林工程有限公司', 'InvoiceNum': '58970228'}, 'log_id': 1513863316591322353}\n"
     ]
    }
   ],
   "source": [
    "## 实践5\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "通用文字识别\n",
    "'''\n",
    "\n",
    "request_url = \" https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice\"\n",
    "# 二进制方式打开图片文件\n",
    "# 1.图片文件准备\n",
    "f = open('cai.jpg', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "# 2. 酬载准备\n",
    "payload={\n",
    "    'access_token':jiaxin_AT,\n",
    "    'image':img,\n",
    "}\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=payload, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa35eb44",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e64b2c7",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9bba0fd",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95a6c5c2",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
